package io.gitee.zhangbinhub.test.reactive.websocket

import io.gitee.zhangbinhub.acp.boot.log.LogAdapter
import io.gitee.zhangbinhub.acp.boot.websocket.reactive.AcpWebSocketServerReactive
import io.gitee.zhangbinhub.acp.core.common.CommonTools.getDefaultCharset
import org.springframework.stereotype.Component
import org.springframework.web.reactive.socket.WebSocketSession
import java.nio.ByteBuffer

@Component
class TestWebSocketServerReactive(logAdapter: LogAdapter) : AcpWebSocketServerReactive(logAdapter, clientIdIndex = 2) {
    override fun getPath(): String {
        return "/websocket/{userId}"
    }

    override fun sessionOpen(session: WebSocketSession) {
        logAdapter.info("【websocket消息】【$clientIp】有新的连接，连接id=$clientId")
        sendMessage("CONNECT_SUCCESS")
    }

    override fun sessionClose(session: WebSocketSession) {
        logAdapter.info("【websocket消息】【$clientIp】【$clientId】连接断开！")
    }

    override fun sessionError(session: WebSocketSession?, throwable: Throwable?) {
        logAdapter.error(if (throwable != null) throwable.message else "", throwable)
        logAdapter.error("【websocket消息】【" + clientIp + "】用户错误,原因:" + if (throwable != null) throwable.message else "")
    }

    override fun receiveMessage(session: WebSocketSession, message: ByteBuffer) {
        logAdapter.info("【websocket消息】【$clientIp】收到客户端【$clientId】发来的【二进制】消息：$message")
        sendMessage(ByteBuffer.wrap("RECEIVE_BINARY_SUCCESS: $message".toByteArray(getDefaultCharset())))
    }

    override fun receiveMessage(session: WebSocketSession, message: String) {
        logAdapter.info("【websocket消息】【$clientIp】收到客户端【$clientId】发来的【文本】消息：$message")
        sendMessage("RECEIVE_TEXT_SUCCESS: $message")
    }
}